
var Global = require('Global');
var Colors = require('Colors');

cc.Class({
    extends: cc.Component,

    properties: {
        tilesX:5,
        tilesY:5,
        powerMax:5,
        bgMusic:cc.AudioClip,
        tiles:{
            default:null,
            type:Array,
        },  
        tilePre:{
            default:null,
            type:cc.Prefab,
        },  
        tileBg:{
            default:null,
            type:cc.Node,
        },
        powers:{
            default:null,
            type:Array,
        },
        powerPre:{
            default:null,
            type:cc.Prefab,
        },
        powerBarBg:{
            default:null,
            type:cc.Node,
        },
        scoreNum:{
            default:null,
            type:cc.Label,
        },
        stars:{
            default:[],
            type:[cc.AudioClip],
        },
        maxNum:{
            default:0,
            visible:false,
        },
        isCal:{
            default:false,
            visible:false,
        },
        tileWidth:{
            default:0,
            visible:false,
        },
        tileHeight:{
            default:0,
            visible:false,
        },
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},
    gameOver(){
        this.panelManager.setOverpanel(true);
        this.panelManager.setGamepanel(false);
    },

    onEnable(){
        console.info('--------game onenable');
        this.scoreNum.string = 0
        //play BGM
        cc.audioEngine.playMusic(this.bgMusic,true);
        //init array of tiles
        this.tiles = new Array();
        for(var i = 0;i < this.tilesY;i++){
            this.tiles[i] = new Array();
            for(var k = 0;k < this.tilesX;k++){
                this.tiles[i][k] = null;
            }
        }
        //init powerTiles
        this.powers = new Array();
        for(var i = 0;i < this.powerMax;i++){
            this.powers[i] = null;
        }
        for(var i = 0;i < this.powerMax;i++){
            var power = cc.instantiate(this.powerPre);
            this.powerBarBg.addChild(power);
            this.powers[i] = power;
            power.color = Colors.power;
        }
        Global.powerNum = this.powerMax;

        var gailv = new Array();
        this.maxNum = 8;
        for(var num = 0;num < this.maxNum - 3;num++){
            gailv[num] = this.maxNum - 3 - num;
        }
        var sum = 0;
        for(var num = 0;num < gailv.length;num++){
            sum += gailv[num];
        }

        this.tileWidth = (this.tileBg.width - 12 - 12 - 12*(this.tilesX-1))/this.tilesX;
        this.tileHeight = (this.tileBg.height - 12 - 12 - 12*(this.tilesY-1))/this.tilesY;
        Global.bgHeight = this.tileBg.height;
        Global.bgWidth = this.tileBg.width;
        Global.xSize = this.tileWidth;
        Global.ySize = this.tileHeight;
        //生成tile
        for(var row = 0;row < this.tilesY;row++){
            for(var col = 0;col < this.tilesX;col++){
                var tile = cc.instantiate(this.tilePre);
                tile.getComponent('Tile').game = this;
                var randomNum = 0;
                while(true){
                    var arr = new Array();
                    var scanArr = new Array();
                    randomNum = Math.random()*sum;
                    var newNum = 0;
                    var min = 0;
                    for(var num = 0;num < gailv.length;num++){
                        if(randomNum >= min && randomNum <= min+gailv[num]){
                            newNum = num+1;
                            break;
                        }else{
                            min = min + gailv[num];
                        }
                    }
                    tile.getComponent('Tile').setNum(newNum,false,false);
                    this.tiles[row][col] = tile;
                    this.scanAround(row,col,-1,-1,newNum,arr,scanArr);
                    if(arr.length < 3){
                        break;
                    }
                }
                tile.getComponent('Tile').setArrPosition(row,col);
                this.tileBg.addChild(tile);
                tile.width = this.tileWidth;
                tile.height = this.tileHeight;
            }
        }

    },

    /*
     * 核心扫描逻辑
     * @param  row  指定行
     * @param  col 制定列
     * @param  lastRow 上次扫描的行
     * @param  lastCol 上次扫描的列
     * @param  num  扫描要比对的数字
     * @param  arr 记录数字相同且彼此相邻的数组
     * @param  scanArr 记录扫描的点的数组
     */
    scanAround(row,col,lastRow,lastCol,num,arr,scanArr){
        if(this.tiles[row][col] == null){
            return;
        }
        var isClear = false;
        if(scanArr == undefined){
            scanArr = new Array();
        }
        //扫描过的节点不再扫描
        if(scanArr.indexOf(row+'#'+col) == -1){
            scanArr.push(row+'#'+col);
        }else{
            return;
        }
        //扫描上
        if(row < this.tilesY - 1 && (lastRow != (row + 1)||lastCol != col) && this.tiles[row + 1][col] != null){
            var nextNum = parseInt(this.tiles[row + 1][col].getComponent('Tile').numLabel.string);
            if(nextNum == num){
                if(arr.indexOf(row+'#'+col) == -1){
                    arr.push(row+'#'+col);
                }
                this.scanAround(row+1,col,row,col,num,arr,scanArr);
                isClear = true;
            }
        }
        //扫描下
        if(row > 0 && (lastRow != (row - 1)||lastCol != col) && this.tiles[row - 1][col] != null){
            var nextNum = parseInt(this.tiles[row - 1][col].getComponent('Tile').numLabel.string);
            if(nextNum == num){
                if(arr.indexOf(row+'#'+col) == -1){
                    arr.push(row+'#'+col);
                }
                this.scanAround(row-1,col,row,col,num,arr,scanArr);
                isClear = true;
            }
        }
        // 扫描左
        if(col > 0 && (lastRow != row||lastCol != (col-1)) && this.tiles[row][col - 1] != null){
            var nextNum = parseInt(this.tiles[row][col - 1].getComponent("Tile").numLabel.string);
            if(nextNum == num){
                if(arr.indexOf(row+"#"+col) == -1){
                    arr.push(row+"#"+col);
                }
                this.scanAround(row,col-1,row,col,num,arr,scanArr);
                isClear = true;
            }
        }
        // 扫描右
        if(col < this.tilesX - 1 && (lastRow != row||lastCol != (col+1)) && this.tiles[row][col + 1] != null){
            var nextNum = parseInt(this.tiles[row][col + 1].getComponent("Tile").numLabel.string);
            if(nextNum == num){
                if(arr.indexOf(row+"#"+col) == -1){
                    arr.push(row+"#"+col);
                }
                this.scanAround(row,col+1,row,col,num,arr,scanArr);
                isClear = true;
            }
        }
        // 四周都不通，但不是出发遍历点，并且数字相同，也加入到数组
        if(!isClear&&(lastRow!=-1&&lastCol!=-1)){
            var curNum = parseInt(this.tiles[row][col].getComponent("Tile").numLabel.string)
            if(curNum==num){
                if(arr.indexOf(row+"#"+col)==-1){
                    arr.push(row+"#"+col);
                }
            }
        }
    },

    operateLogic(touchRow,touchCol,curNum,isFirstCall){
        var arr = new Array();
        var scanArr = new Array();
        this.scanAround(touchRow,touchCol,-1,-1,curNum,arr,scanArr);
        if(arr.length >= 3){
            var addScore = 0;
            for(var index = 0,len = arr.length;index < len;index++){
                var row = arr[index].split('#')[0];
                var col = arr[index].split('#')[1];
                addScore += parseInt(this.tiles[row][col].getComponent('Tile').numLabel.string * 10); //销毁的十倍
                if(row != touchRow||col != touchCol){
                    //销毁
                    this.tiles[row][col].getComponent('Tile').destoryTile();
                    this.tiles[row][col] = null;
                }else{
                    this.tiles[row][col].getComponent('Tile').setNum((curNum+1),false,true);
                    this.maxNum = curNum+1 > this.maxNum?curNum+1:this.maxNum;
                }
            }
            //更新分数
            this.scoreNum.string = parseInt(this.scoreNum.string) + addScore;
            this.scheduleOnce(function(){
                this.moveAllTileDown();
            },0.1);

            if(!isFirstCall){
                //能量条补充
                if(Global.powerNum < this.powerMax){
                    this.powers[Global.powerNum].color = Colors.power;
                // this.powers[Global.powerNum].node.runAction(cc.sequence(cc.tintTo(Colors.power)));
                    Global.powerNum++;
                }
                Global.combo++;
                if(Global.combo <= this.stars.length){
                cc.audioEngine.playEffect(this.stars[Global.combo - 1]);
                }else{
                cc.audioEngine.playEffect(this.stars[this.stars.length - 1]);
                }
            }
            return true;
        }else{
            this.isCal = false;
        }
        return false;
    },

    //所有方块下移
    moveAllTileDown(){
        //遍历下移 待优化
        for(var col = 0;col < this.tilesX;col++){
            for(var row = 0;row < this.tilesY;row++){
                if(this.tiles[row][col] != null){
                    for(var row1 = row;row1 > 0;row1--){
                        if(this.tiles[row1 - 1][col] == null){
                            //下移
                            this.tiles[row1 - 1][col] = this.tiles[row1][col];
                            this.tiles[row1][col] = null;
                            this.tiles[row1 - 1][col].getComponent('Tile').moveTo(row1 - 1,col);
                        }
                    }
                }
            }
        }

        //0.3秒后产生新方块
        this.scheduleOnce(function(){
            var gailv = new Array();
            for(var num = 0;num < this.maxNum - 3;num++){
                gailv[num] = this.maxNum - 3 - num;
            }
            var sum = 0;
            for(var num = 0;num < gailv.length;num++){
                sum += gailv[num];
            }
            for(var col = 0;col < this.tilesX;col++){
                for(var row = 0;row < this.tilesY;row++){
                    if(this.tiles[row][col] == null){
                        var tile = cc.instantiate(this.tilePre);
                        tile.getComponent("Tile").game = this;
                        tile.width = this.tileWidth;
                        tile.height = this.tileHeight;
                        var randomNum = Math.random()*sum;
                        var newNum = 0;
                        var min = 0;
                        for(var num = 0;num < gailv.length;num++){
                            if(randomNum >= min && randomNum<=min + gailv[num]){
                                newNum = num + 1;
                                break;
                            }else{
                                min = min + gailv[num];
                            }
                        }
                        tile.getComponent('Tile').setNum(newNum,false,false);
                        tile.getComponent('Tile').newTile(row,col);
                        this.tiles[row][col] = tile;
                        this.tileBg.addChild(tile);
                    }
                }
            }

            //0.5秒遍历执行逻辑
            this.scheduleOnce(function(){
                var isSearch = false;
                for(col = 0;col < this.tilesX;col++){
                    for(row = 0;row <this.tilesY;row++){
                        if(!isSearch){
                            isSearch = this.tiles[row][col] != null && this.operateLogic(row,col,parseInt(this.tiles[row][col].getComponent('Tile').numLabel.string),false);
                        }
                    }
                }
            },0.5);

        },0.3);

    },

    onDisable(){

        cc.audioEngine.stopMusic(this.bgMusic);
        for(var i = 0;i < this.powers.length;i++){
            this.powers[i].destroy();
        }
        for(var i = 0;i < this.tilesY;i++){
            for(var k = 0;k < this.tilesX;k++){
             this.tiles[i][k].destroy();
            }
        }
    },

});
